﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Kokomo.Environment.Hosting.Settings;

namespace Kokomo.Environment.Hosting.Services
{
	class RecentDocumentService : ServiceObjectBase
	{
		public RecentDocumentService(EditorApplication editorApplication)
			: base(editorApplication)
		{
			this._recentDocuments = new ObservableCollection<RecentDocumentEntry>();
			var recentDocumentPaths = editorApplication.SettingsManager.GetSettings<GeneralSettings>().RecentDocumentList;
			if (recentDocumentPaths != null)
			{
				foreach (var path in recentDocumentPaths)
				{
					RecentDocumentEntry entry = new RecentDocumentEntry(path);
					this._recentDocuments.Add(entry);
				}
			}
		}

		private ObservableCollection<RecentDocumentEntry> _recentDocuments;

		public IEnumerable<RecentDocumentEntry> RecentDocuments { get { return this._recentDocuments; } }

		private RecentDocumentEntry FindEntryForPath(string documentPath)
		{
			if (documentPath == null) throw new ArgumentNullException("documentPath");

			foreach (var entry in this.RecentDocuments)
			{
				if (entry.DocumentPath == documentPath) return entry;
			}

			return null;
		}
		public void OnOpenDocument(string documentPath)
		{
			// Search for document in list
			{
				RecentDocumentEntry entry = this.FindEntryForPath(documentPath);
				if (entry != null)
				{
					this._recentDocuments.Remove(entry);
				}
				else
				{
					entry = new RecentDocumentEntry(documentPath);
				}
				this._recentDocuments.Insert(0, entry);
			}

			// Save settings
			List<string> recentDocumentPaths = new List<string>(this._recentDocuments.Count);
			foreach (var entry in this.RecentDocuments)
			{
				recentDocumentPaths.Add(entry.DocumentPath);
			}

			GeneralSettings settings = this.EditorApplication.SettingsManager.GetSettings<GeneralSettings>();
			settings.RecentDocumentList = recentDocumentPaths.ToArray();
			settings.Save();
		}
	}
}
